<template>

  <div class="app-container">

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="最终发布"/>
    </el-steps>

    <el-card class="box-card">
    <!--  课程标题  -->
    <el-form label-width="100px" :model="courseInfo" :rules="rules" ref="courseInfo">
      <el-form-item label="课程标题" style="width: 620px" prop="title">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 所属分类 TODO -->
      <el-form-item label="课程分类" prop="subjectId">
        <!-- 一级分类 -->
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="一级分类" @change="subjectOneChanged">
          <el-option
            v-for="subjectOne in subjectOneList"
            :key="subjectOne.id"
            :label="subjectOne.title"
            :value="subjectOne.id"/>
        </el-select>

        <!-- 二级分类 -->

        <el-select v-model="courseInfo.subjectId" placeholder="请选择二级分类">
          <el-option
            v-for="subjectTwo in subjectTwoList"
            :key="subjectTwo.id"
            :label="subjectTwo.title"
            :value="subjectTwo.id"/>
        </el-select>

      </el-form-item>


      <!-- 课程讲师 TODO -->
      <el-form-item label="课程讲师" prop="teacherId">
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>


      <el-form-item label="总课时" prop="lessonNum">
        <el-input-number :min="0" v-model="courseInfo.lessonNum"  controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!-- 课程简介 TODO -->
      <el-form-item label="课程简介" style="width: 720px"  prop="description">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <!-- 课程封面 TODO -->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/edu_oss/upload/avatar'"
          class="avatar-uploader">
          <img :src="courseInfo.cover" v-if="courseInfo.cover" class="avatar">
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格"  prop="price">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/>
      </el-form-item>

      <el-form-item style="text-align: center; padding-top: 50px; padding-right: 150px">
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate('courseInfo')">下一步</el-button>
      </el-form-item>
    </el-form>
    </el-card>
  </div>
</template>

<script>
import course from '@/api/edu/course'
import subject from '@/api/edu/subject'
import Tinymce from '@/components/Tinymce'

export default {
  // 声明组件
  components: { Tinymce },
  data() {
    return {
      saveBtnDisabled: false,
      courseInfo: {
        title: '',
        subjectId: '',
        subjectParentId: '',
        teacherId: '',
        lessonNum: 1,
        description: '',
        cover: 'https://guli-college-test.oss-cn-shenzhen.aliyuncs.com/bg.png',
        price: 0,
      },
      courseId: '',
      BASE_API: process.env.BASE_API,
      teacherList: [],
      subjectOneList: [],
      subjectTwoList: [],
      rules:{
        title: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
        subjectId: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        teacherId: [{ required: true, message: '请选择讲师', trigger: 'blur' }],
        lessonNum: [{ required: true, message: '请输入课时数', trigger: 'blur' }],
        description: [{ required: true, message: '请添加课程简介', trigger: 'blur' }],
        price: [{ required: true, message: '请添加价格', trigger: 'blur' }],
      },
    }
  },
  created() {
    // 获取路径中的id
    if (this.$route.params && this.$route.params.id) {
      this.courseId = this.$route.params.id
      this.getInfo()
    } else {
      // 初始化所有讲师
      this.getAllTeacher()

      // 初始化一级分类
      this.getOneSubject()
    }
  },
  methods: {
    getInfo() {
      course.getCourseInfoId(this.courseId)
        .then(res => {
          this.courseInfo = res.data.courseInfoVO
          // 查询所有分类
          subject.getAllSubject()
            .then(res => {
                // 获取所有一级分类
              this.subjectOneList = res.data.list
              // 遍历所有的一级分类数组，比较点courseInfo里面一级分类id
              for (var i = 0; i < this.subjectOneList.length; i++) {
                // 获取每一个一级分类
                var oneSubject = this.subjectOneList[i]
                if (oneSubject.id == this.courseInfo.subjectParentId) {
                  this.subjectTwoList = oneSubject.children
                }
              }
            })
          this.getAllTeacher()
        })
    },
    // 上传封面成功调用的方法
    handleAvatarSuccess(res, file) {
      this.courseInfo.cover = res.data.url
      this.$message({
        type: 'success',
        message: '上传课程封面成功'
      })
    },
    // 上传之前调用的方法
    beforeAvatarUpload(file) {
      const  isJPG = file.type === 'image/jpeg'
      const  isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是jpg格式')
      }
      if (!isLt2M) {
        this.$message.error('上传图片不能大于2M')
      }
      return isLt2M && isJPG
    },
    // 点击一级分类触发change，显示对应二级分类
    subjectOneChanged(value) {

      for (let i = 0; i < this.subjectOneList.length; i++) {
        var oneSubject = this.subjectOneList[i]
        if (oneSubject.id === value) {
          // 从一级分类中获取所有的二级分类
          this.subjectTwoList = oneSubject.children
          // 清空二级分类
          this.courseInfo.subjectId = ''
        }
      }
    },
    // 查询所有的一级分类
    getOneSubject() {
      subject.getAllSubject()
        .then(res => {
          this.subjectOneList = res.data.list
        })
    },
    // 查询所有的讲师
    getAllTeacher() {
      course.getListTeacher()
        .then(res => {
          this.teacherList = res.data.items
        })
    },
    // 添加课程信息
    addCourse(){
      course.addCourseInfo(this.courseInfo)
        .then(res => {
          this.$message({
            type: 'success',
            message: '添加课程信息成功'
          });
          // 跳转到第二步
          this.$router.push({path: '/course/chapter/' + res.data.courseId})
        })
    },
    // 修改课程信息
    updateCourse() {
        course.updateCourseInfo(this.courseInfo)
          .then(res => {
            this.$message({
              type: 'success',
              message: '修改信息成功'
            });
            // 跳转到第二步
            this.$router.push({path: '/course/chapter/' + this.courseId})
          })
    },
    // 保存或修改数据
    saveOrUpdate(courseInfo) {
      // 判断是添加还是修改
      this.$refs[courseInfo].validate((valid) => {
        if (valid) {
          if (!this.courseInfo.id){
            this.addCourse()
          }else {
            this.updateCourse()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });


    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 350px;
  height: 200px;
  display: block;
}
.tinymce-container {
  line-height: 29px;
}
</style>

